package com.atguigu.gmall.common.service;

import com.alibaba.fastjson.JSON;
import com.atguigu.gmall.common.model.GmallCorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class RabbitService {

    //使用的是模板设计模式
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private RedisTemplate redisTemplate;

    //发送消息
    public Boolean sendMsg(String exchange,String routingKey,Object msg){

        GmallCorrelationData gmallCorrelationData = new GmallCorrelationData();
        String correlationDataId = UUID.randomUUID().toString();
        gmallCorrelationData.setId(correlationDataId);  //唯一标识
        gmallCorrelationData.setExchange(exchange);
        gmallCorrelationData.setRoutingKey(routingKey);
        gmallCorrelationData.setMessage(msg);
        //将实体类存储的缓存
        redisTemplate.opsForValue().set(correlationDataId, JSON.toJSONString(gmallCorrelationData),10, TimeUnit.MINUTES);
        //发送消息
        //rabbitTemplate.convertAndSend(exchange,routingKey,msg);
        rabbitTemplate.convertAndSend(exchange,routingKey,msg,gmallCorrelationData);
        //默认返回
        return true;
    }

    //发送延迟消息
    public Boolean sendDelayMsg(String exchange,String routingKey,Object msg,int delayTime){
        //发送消息的时候 可能会产生不到交换机的情况 所以要做重试
        GmallCorrelationData gmallCorrelationData = new GmallCorrelationData();
        String correlationDataId = UUID.randomUUID().toString();
        gmallCorrelationData.setId(correlationDataId);  //唯一标识
        gmallCorrelationData.setExchange(exchange);
        gmallCorrelationData.setRoutingKey(routingKey);
        gmallCorrelationData.setMessage(msg);
        //赋值延迟消息
        gmallCorrelationData.setDelay(true);
        gmallCorrelationData.setDelayTime(delayTime);

        //消息写到缓存
        redisTemplate.opsForValue().set(correlationDataId, JSON.toJSONString(gmallCorrelationData),10, TimeUnit.MINUTES);

        //发送延迟消息
        rabbitTemplate.convertAndSend(exchange,routingKey,msg,(message) -> {
            //设置延迟时间 delayTime传几就是几秒 1 = 1秒
            message.getMessageProperties().setDelay(delayTime*1000);
            return message;
        },gmallCorrelationData);
        return true;
    }
}
